import sys
from pathlib import Path
import json
from dataclasses import dataclass
from typing import List, Optional

sys.path.append(str(Path(__file__).parent.parent))
from reqapi.api import BaseApi

@dataclass
class CommodityItem:
    """商品项"""
    commodityId: int  # 商品ID
    commodityIdPrice: str  # 商品价格
    templateId: int  # 模板ID

@dataclass
class BatchSellOrderRequest:
    """批量卖单请求"""
    buyNumber: int  # 购买数量
    commodityList: List[CommodityItem]  # 商品列表
    orderSubType: int  # 订单子类型
    paySellAmount: str  # 支付卖出金额
    templateId: int  # 模板ID
    unitPrice: str  # 单价
    Sessionid: Optional[str] = None  # 会话ID，可选

@dataclass
class BatchSellOrderResponse:
    """批量卖单响应"""
    code: int
    msg: str
    timestamp: int
    data: Optional['BatchSellOrderData']
    
    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建响应对象"""
        response_data = None
        if data.get('data'):
            response_data = BatchSellOrderData.from_dict(data.get('data'))
        
        return cls(
            code=data.get('code'),
            msg=data.get('msg'),
            timestamp=data.get('timestamp'),
            data=response_data
        )

@dataclass
class BatchSellOrderData:
    """批量卖单响应数据"""
    orderNo: str  # 订单号
    payOrderNo: str  # 支付订单号
    payErrorCode: Optional[str]  # 支付错误码
    payErrorMessage: Optional[str]  # 支付错误信息
    payString: Optional[str]  # 支付字符串
    type: Optional[str]  # 类型
    batchOrderNo: Optional[str]  # 批量订单号
    notifyUrl: Optional[str]  # 通知URL
    waitPaymentDataNo: str  # 等待支付数据号
    
    @classmethod
    def from_dict(cls, data: dict):
        """从字典创建数据对象"""
        return cls(
            orderNo=data.get('orderNo'),
            payOrderNo=data.get('payOrderNo'),
            payErrorCode=data.get('payErrorCode'),
            payErrorMessage=data.get('payErrorMessage'),
            payString=data.get('payString'),
            type=data.get('type'),
            batchOrderNo=data.get('batchOrderNo'),
            notifyUrl=data.get('notifyUrl'),
            waitPaymentDataNo=data.get('waitPaymentDataNo')
        )

class BatchSellOrderApi(BaseApi):
    """批量卖单API"""
    
    def create_batch_order(self, request: BatchSellOrderRequest):
        """创建批量卖单
        
        Args:
            request: 批量卖单请求对象
            
        Returns:
            BatchSellOrderResponse: 批量卖单响应
            
        Raises:
            Exception: 请求失败或业务处理失败时抛出异常
        """
        # API端点
        endpoint = "/api/youpin/bff/trade/v1/order/batch/sell/createBatchOrder"
        url = f"{self.BASE_URL}{endpoint}"
        
        # 构建请求数据
        request_data = {
            "buyNumber": request.buyNumber,
            "commodityList": [
                {
                    "commodityId": item.commodityId,
                    "commodityIdPrice": item.commodityIdPrice,
                    "templateId": item.templateId
                } for item in request.commodityList
            ],
            "orderSubType": request.orderSubType,
            "paySellAmount": request.paySellAmount,
            "templateId": request.templateId,
            "unitPrice": request.unitPrice,
            "Sessionid": request.Sessionid or self.device_id  # 如果未提供，使用device_id
        }
        # 获取请求头
        headers = self.common_headers.copy()
        print("=" * 50)
        print("批量卖单API - 请求URL:")
        print(url)
        print("\n批量卖单API - 请求头:")
        print(json.dumps(headers, indent=2, ensure_ascii=False))
        print("\n批量卖单API - 请求体:")
        print(json.dumps(request_data, indent=4, ensure_ascii=False))
        print("=" * 50)
        try:
            # 统一用拦截器处理请求和响应
            response = self.interceptor.send_request(url, json=request_data, headers=headers, need_encrypt=False)
            if isinstance(response, dict):
                result = response
            elif hasattr(response, 'json'):
                result = response.json()
            else:
                result = response
            print("\n" + "=" * 50)
            print("批量卖单API - 响应内容:")
            print(json.dumps(result, indent=4, ensure_ascii=False))
            print("=" * 50)
            if result.get('code') != 0 and result.get('code') != 10001:
                raise Exception(f"业务处理失败: {result.get('msg')}")
            return BatchSellOrderResponse.from_dict(result)
        except Exception as e:
            print(f"请求失败: {e}")
            return None


def main():
    """测试批量卖单API"""
    try:
        # 使用UTDID生成器生成device_id
        # utdid_generator = UTDIDGenerator()
        # device_id = utdid_generator.get_utdid()
        from com.db.order_account_manager import OrderAccountManager
        account_manager = OrderAccountManager()
        account = account_manager.get_account_by_id(1)
            
        if not account:
            print("无法获取ID为1的账号")
            return
            
        device_id = account.get('device_id', '')
        auth_token = account.get('uu_token', '')
        uk = account.get('uk', '')
        
        # 创建API实例
        api = BatchSellOrderApi(
            device_token=device_id,  # 使用生成的device_id作为device_token
            device_id=device_id,
            auth_token=auth_token,
            uk=uk
        )
        
        # 创建商品列表
        commodity_list = [
            CommodityItem(
                commodityId=1257926550,
                commodityIdPrice="0.58",
                templateId=109560
            )
        ]
        
        # 创建请求对象
        request = BatchSellOrderRequest(
            buyNumber=1,
            commodityList=commodity_list,
            orderSubType=9,
            paySellAmount="0.58",
            templateId=109560,
            unitPrice="0.6",
            Sessionid=device_id
        )
        
        # 发送请求
        result = api.create_batch_order(request)
        
        # 修正：先判断返回值再打印，保持原有结构不变
        if result is None:
            print("批量卖单创建失败，可能是登录信息失效或接口返回错误。")
        else:
            print("批量卖单创建成功！")
            print(f"订单号: {result.data.orderNo}")
            print(f"支付订单号: {result.data.payOrderNo}")
            print(f"等待支付数据号: {result.data.waitPaymentDataNo}")

    except Exception as e:
        print(f"错误: {e}")


if __name__ == "__main__":
    main()
